package com.yiyibook.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yiyibook.entity.BookSmallStyle;
import com.yiyibook.mapper.BookMapper;
import com.yiyibook.util.BookNum;
import com.yiyibook.util.FieldErrorMsg;
import com.yiyibook.util.FileUploadUtil;
import com.yiyibook.util.Msg;
import com.yiyibook.entity.Book;
import com.yiyibook.service.BookService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * 图书信息 Controller
 *
 * @author yi.wu
 * @date 2019-10-14
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @GetMapping("/lastNum")
    public String selectLastNum(){
        String bookNum = "";
        Book b1 = bookService.selectLastNum();
        // 给书籍添加流水号
        if(b1 == null){
            bookNum = BookNum.setBookNum(null);
        }else {
            bookNum = BookNum.setBookNum(b1.getBookNum());
        }
        return bookNum;
    }

    @PostMapping("/insert")
    public Msg insertBook(@Valid Book book, @RequestParam(name = "bookImageUpload")MultipartFile bookImageUpload, BindingResult result){
        if (result.hasErrors()) {
            //校验失败，显示校验失败的错误信息
            return Msg.fail().add("errorMsg", FieldErrorMsg.errorMsg(result));
        }else{
            // 获取数据库中最后一本书籍的流水号
            Book b1 = bookService.selectLastNum();

            // 给书籍添加流水号
            if(b1 == null){
                book.setBookNum(BookNum.setBookNum(null));
            }else {
                book.setBookNum(BookNum.setBookNum(b1.getBookNum()));
            }

            // 校验数据库中是否已存在该书籍
            Book b2 = bookService.selectByBookNum(book.getBookNum());
            if(b2 != null){
                return Msg.fail().add("errorMsg","该书籍已存在！");
            }
            Msg msg = fileUploadUtil.uploadFile(bookImageUpload);
            if(msg.getCode() == Msg.SUCCESS){
                String fileTrueName = (String)msg.getExtend().get("fileTrueName");
                book.setBookImage(fileTrueName);
                int i = bookService.insert(book);
                if(i>0){
                    return Msg.success();
                }else {
                    return Msg.fail().add("errorMsg","添加失败，请重试或联系技术人员！");
                }
            }
            return msg;
        }
    }

    @RequestMapping("/getAll")
    public Msg getAll(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                      @RequestParam(defaultValue = "1")Integer smallStyleId){
        PageHelper.startPage(pageNum,10);
        List<Book> bookList = bookService.selectByBookSmallStyleId(smallStyleId);
        //传入连续显示的页数
        PageInfo page = new PageInfo(bookList,5);
        return Msg.success().add("pageInfo",page);
    }

    @RequestMapping("/selectByCondition")
    public Msg selectByCondition(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                 @RequestParam(defaultValue = "1")Integer smallStyleId,
                                 @RequestParam(required = false) String condition){
        Book book = new Book();
        book.setIntroduction(condition);
        book.setAuthor(condition);
        book.setPublishingCompany(condition);
        book.setBookTitle(condition);
        // 分页
        PageHelper.startPage(pageNum,10);
        List<Book> bookList = bookService.selectByCondition(book);
        //传入连续显示的页数
        PageInfo page = new PageInfo(bookList,5);
        return Msg.success().add("pageInfo",page);
    }

    @PostMapping("/update")
    public Msg updateByCondition(@Valid Book book, @RequestParam(name = "bookImageUpload")MultipartFile bookImageUpload, BindingResult result){
        if (result.hasErrors()) {
            //校验失败，显示校验失败的错误信息
            return Msg.fail().add("errorMsg", FieldErrorMsg.errorMsg(result));
        }else{
            if (!bookImageUpload.isEmpty()) {
                Msg msg = fileUploadUtil.uploadFile(bookImageUpload);
                if(msg.getCode() == Msg.SUCCESS) {
                    String fileTrueName = (String) msg.getExtend().get("fileTrueName");
                    book.setBookImage(fileTrueName);
                }
            }
            int i = bookService.updateByCondition(book);
            if(i>0){
                return Msg.success();
            }else {
                return Msg.fail().add("errorMsg","修改失败，请重试或联系技术人员！");
            }
        }
    }

    @GetMapping("/delete")
    public Msg deleteById(Integer bookId){
        Book book = bookService.selectById(bookId);
        if(book.getStock() > 0){
            return Msg.fail().add("errorMsg","图书库存不为0 不能删除图书！");
        }
        int i = bookService.deleteById(bookId);
        if(i>0){
            return Msg.success();
        }else {
            return Msg.fail().add("errorMsg","网络波动，请重试或联系技术人员！");
        }
    }

    @GetMapping("/deleteAny")
    public Msg deleteAny(String bookIds){
        // 保存 无法被删除的 图书（即图书库存不为0的情况）
        String bookTitle = "";
        // 记录 是否删除成功
        int j = 0;
        String[] split = bookIds.split(", ");
        Integer[] bookIdsArr = new Integer[split.length];
        for (int i = 0; i < bookIdsArr.length; i++) {
            bookIdsArr[i] = Integer.parseInt(split[i]);
        }
        for (int i = 0; i < bookIdsArr.length; i++) {
            Book book = bookService.selectById(bookIdsArr[i]);
            if(book.getStock() > 0){
                if(i == bookIdsArr.length-1){
                    bookTitle = bookTitle + book.getBookTitle();
                }else{
                    bookTitle = bookTitle + book.getBookTitle()+ ",";
                }
            }else{
                j = bookService.deleteById(bookIdsArr[i]);
            }
        }
        if(j > 0){
            return Msg.success().add("successMsg","删除成功");
        }else if(j == 0){
            return Msg.fail().add("errorMsg","以下 " + bookTitle + " 图书库存不为0，无法删除，请先清0图书库存!");
        }else {
            return Msg.fail().add("errorMsg","网络波动，请重试");
        }

    }

    @RequestMapping("/showNew")
    public Msg showNew(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum){
        // 分页
        PageHelper.startPage(pageNum,10);
        List<Book> bookList = bookService.selectNew();
        //传入连续显示的页数
        PageInfo page = new PageInfo(bookList,5);
        return Msg.success().add("pageInfo",page);
    }

    @GetMapping("/selectOne")
    public Book selectById(Integer bookId){
        return bookService.selectById(bookId);
    }

    @GetMapping("/showPop")
    public Msg showPop(){
        List<Book> bookList = bookService.selectPop();
        return Msg.success().add("bookList",bookList);
    }
}
